//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace Microsoft.Office.OneNote.UnitTests
{
	public class TestUtils
	{
		/// <summary>
		///  Helper method to create a test notebook:
		/// </summary>
		public static Notebook CreateEmptyNotebook()
		{
			NotebookRoot root = OneNote.Application.NotebookRoot;

			// Create a new notebook:
			string testNotebook = Path.Combine(Path.GetTempPath(), "OneNote OM Test");
			if (Directory.Exists(testNotebook))
			{
				int attempt = 0;

				bool success = false;
				while (!success)
				{
					testNotebook = Path.Combine(Path.GetTempPath(), "OneNote OM Test" + attempt);
					if (!Directory.Exists(testNotebook))
					{
						success = true;
					}

					attempt++;
				}
			}

			using (HierarchyTransaction addNotebookTransaction = new HierarchyTransaction(root))
			{
				root.AppendChild(new Notebook(testNotebook));
				root.Commit();

				// Great!  Now let's find it:

				int notebookCount = root.GetChildCount();
				for (int iNotebook = 0; iNotebook < notebookCount; iNotebook++)
				{
					ANode child = root.GetChild(iNotebook);
					if (child is Notebook && ((Notebook) child).Path == testNotebook)
					{
						return ((Notebook) child);
					}
				}
			}

			return null;
		}

		// Helper method to close and delete a notebook:
		public static void CloseAndDeleteNotebook(Notebook notebook)
		{
			NotebookRoot root = OneNote.Application.NotebookRoot;

			int attempts = 0;
			bool success;

			do
			{
				success = true;
				attempts++;

				using (HierarchyTransaction removeNotebookTransaction = new HierarchyTransaction(root))
				{
					root.DeleteChild(notebook);
					root.Commit();

					for (int iNotebook = 0; iNotebook < root.GetChildCount(); iNotebook++)
					{
						ANode child = root.GetChild(iNotebook);
						if (child is Notebook && ((Notebook) child).Path == notebook.Path)
						{
							notebook = (Notebook) child;
							success = false;

							Thread.Sleep(500);
							break;
						}
					}
				}
			}
			while (!success && attempts < 5);

			if (Directory.Exists(notebook.Path))
			{
				int attempt = 0;
				success = false;
				while (!success && attempt < 5)
				{
					try
					{
						Directory.Delete(notebook.Path, true /* recursive */);
						success = true;
					}
					catch (Exception)
					{
						Thread.Sleep(500);
					}

					attempt++;
				}
			}
		}
	}
}
